// 全局变量
let currentGroup = '';
let taskModal = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    taskModal = new bootstrap.Modal(document.getElementById('taskModal'));
    loadTaskGroups();
    loadTasks();
});

// 加载任务组列表
async function loadTaskGroups() {
    try {
        const response = await fetch('/api/task-groups');
        const groups = await response.json();
        
        const groupsList = document.getElementById('taskGroups');
        groupsList.innerHTML = `
            <a href="#" class="list-group-item list-group-item-action ${currentGroup === '' ? 'active' : ''}" 
               onclick="selectGroup('')">
                全部
            </a>
        `;
        
        groups.forEach(group => {
            groupsList.innerHTML += `
                <a href="#" class="list-group-item list-group-item-action ${currentGroup === group ? 'active' : ''}"
                   onclick="selectGroup('${group}')">
                    ${group}
                </a>
            `;
        });
    } catch (error) {
        console.error('加载任务组失败:', error);
    }
}

// 选择任务组
function selectGroup(group) {
    currentGroup = group;
    document.getElementById('currentGroup').textContent = group || '全部';
    loadTasks();
    loadTaskGroups();
}

// 加载任务列表
async function loadTasks() {
    try {
        const url = currentGroup ? `/api/tasks?group=${currentGroup}` : '/api/tasks';
        const response = await fetch(url);
        const tasks = await response.json();
        
        const taskList = document.getElementById('taskList');
        taskList.innerHTML = '';
        
        tasks.forEach(task => {
            taskList.innerHTML += `
                <tr>
                    <td>${task.name}</td>
                    <td>${task.cron_expr}</td>
                    <td>${task.group_name}</td>
                    <td>
                        <span class="task-status-${task.status}">
                            ${task.status === 1 ? '启用' : '禁用'}
                        </span>
                    </td>
                    <td>${formatTime(task.last_run_time)}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editTask(${task.id})">
                            编辑
                        </button>
                        <button class="btn btn-sm btn-outline-${task.status === 1 ? 'warning' : 'success'}"
                                onclick="toggleTaskStatus(${task.id}, ${task.status})">
                            ${task.status === 1 ? '禁用' : '启用'}
                        </button>
                    </td>
                </tr>
            `;
        });
    } catch (error) {
        console.error('加载任务列表失败:', error);
    }
}

// 显示创建任务模态框
function showCreateTaskModal() {
    document.getElementById('taskForm').reset();
    document.getElementById('taskId').value = '';
    document.getElementById('taskModalTitle').textContent = '新建任务';
    if (currentGroup) {
        document.getElementById('groupName').value = currentGroup;
    }
    taskModal.show();
}

// 编辑任务
async function editTask(taskId) {
    try {
        const response = await fetch(`/api/tasks/${taskId}`);
        const task = await response.json();
        
        document.getElementById('taskId').value = task.id;
        document.getElementById('taskName').value = task.name;
        document.getElementById('groupName').value = task.group_name;
        document.getElementById('cronExpr').value = task.cron_expr;
        document.getElementById('command').value = task.command;
        
        document.getElementById('taskModalTitle').textContent = '编辑任务';
        taskModal.show();
    } catch (error) {
        console.error('加载任务详情失败:', error);
    }
}

// 保存任务
async function saveTask() {
    const taskId = document.getElementById('taskId').value;
    const task = {
        name: document.getElementById('taskName').value,
        group_name: document.getElementById('groupName').value,
        cron_expr: document.getElementById('cronExpr').value,
        command: document.getElementById('command').value,
        status: 1
    };
    
    try {
        const url = taskId ? `/api/tasks/${taskId}` : '/api/tasks';
        const method = taskId ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(task)
        });
        
        if (response.ok) {
            taskModal.hide();
            loadTasks();
            loadTaskGroups();
        } else {
            const error = await response.json();
            alert('保存失败: ' + error.error);
        }
    } catch (error) {
        console.error('保存任务失败:', error);
        alert('保存失败: ' + error.message);
    }
}

// 切换任务状态
async function toggleTaskStatus(taskId, currentStatus) {
    try {
        const response = await fetch(`/api/tasks/${taskId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                status: currentStatus === 1 ? 2 : 1
            })
        });
        
        if (response.ok) {
            loadTasks();
        } else {
            const error = await response.json();
            alert('操作失败: ' + error.error);
        }
    } catch (error) {
        console.error('切换任务状态失败:', error);
        alert('操作失败: ' + error.message);
    }
}

// 格式化时间
function formatTime(timeStr) {
    if (!timeStr) return '-';
    const date = new Date(timeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
} 